package cn.xanderye.eureka.client.controller;

import cn.xanderye.eureka.client.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;


/**
 * Created on 2019/12/25.
 *
 * @author 叶振东
 */
@RestController
public class HelloController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Registration registration;

    @Autowired
    DiscoveryClient client;

    @Value("${server.port}")
    Integer serverPort;

    @GetMapping("hello")
    public String hello() throws Exception {
        ServiceInstance instance = serviceInstance();
        // 模拟断路
        /*int sleepTime = new Random().nextInt(2000);
        logger.info("sleepTime:" + sleepTime);
        Thread.sleep(sleepTime);*/
        logger.info("/hello,host:" + instance.getHost() + ", server_id:" + instance.getServiceId());
        return "Hello World";
    }

    @GetMapping("hello1")
    public String hello(@RequestParam String name) {
        return "Hello " + name;
    }

    @GetMapping("hello2")
    public User hello(@RequestHeader String name, @RequestHeader Integer age) {
        return new User(name, age);
    }

    @PostMapping("hello3")
    public String hello(@RequestBody User user) {
        return "Hello " + user.getName() + "," + user.getAge();
    }

    private ServiceInstance serviceInstance() {
        List<ServiceInstance> list = client.getInstances(registration.getServiceId());
        if (list != null && list.size() > 0) {
            for (ServiceInstance instance : list) {
                if (instance.getPort() == serverPort) {
                    return instance;
                }
            }
        }
        return null;
    }
}
